<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <!-- vscode 的代码片段功能 -->
    <link
      href="https://cdn.bootcdn.net/ajax/libs/nprogress/0.2.0/nprogress.css"
      rel="stylesheet"
    />
  </head>
  <body>
    <button>王者荣耀</button>
    <button>英雄联盟</button>

    <script src="https://cdn.bootcdn.net/ajax/libs/axios/1.1.2/axios.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/nprogress/0.2.0/nprogress.js"></script>
    <script>
      //获取按钮
      let btns = document.querySelectorAll("button");

      //axios 的二次封装

      //创建 axios 实例   
      let xhAxios = axios.create({
        baseURL: "http://api.xiaohigh.com",
      });

      //拦截器                          设置成功的拦截器
      xhAxios.interceptors.request.use((config) => {
        // 显示进度条
        NProgress.start();
        //返回 config 对象
        return config;
      });

      //响应拦截器
      xhAxios.interceptors.response.use(
        (response) => {
          //关闭进度条
          NProgress.done();
          // 返回 response 对象
          return response.data;
        },
        (err) => {
          //错误的统一处理
          alert("请求错误~~~");
          //抛出一个错误
          throw err;
          //了解
          // return new Promise(() => {});
        }
      );

      btns[0].onclick = async function () {
        try {
          let response = await xhAxios.get("/hero");
          console.log(response);
        } catch (e) {
          console.log('出错啦~~~');
        }
      };

      btns[1].onclick = async function () {
        let response = await xhAxios.get("/lo");
        console.log(response);
      };
    </script>
  </body>
</html>
